import DataTable from '@/components/comp/DataTable';
import MapList from '@/components/data/mapList.js';
import ChartTypes from '@/components/data/chartType.js';
import DataSourceUtil from '@/components/util/dataSourceUtil.js';
import ChartDataUtil from '@/components/util/chartDataUtil.js';
import ExportUtil from '@/components/util/exportUtil.js';
import echarts from 'echarts';
import 'echarts-wordcloud';

import LineOption from '@/components/chart/LineOption';
import BarOption from '@/components/chart/BarOption';
import PieOption from '@/components/chart/PieOption';
import ScatterOption from '@/components/chart/ScatterOption';
import RadarOption from '@/components/chart/RadarOption';
import TreeOption from '@/components/chart/TreeOption';
import MapOption from '@/components/chart/MapOption';
import FunnelOption from '@/components/chart/FunnelOption';
import GaugeOption from '@/components/chart/GaugeOption';
import WordCloudOption from '@/components/chart/WordCloudOption';
import GraphOption from '@/components/chart/GraphOption';

import ThemeList from '@/components/data/themeList.js';
import ColorPicker from '@/components/comp/ColorPicker';
export default {
  name: 'ChartEditor',
  props: {
    langType: {
      type: String,
      default: window.localStorage.getItem('langType'),
    },
  },
  components: {
    'data-table': DataTable,
    'bi-line': LineOption,
    'bi-bar': BarOption,
    'bi-pie': PieOption,
    'bi-scatter': ScatterOption,
    'bi-radar': RadarOption,
    'bi-tree': TreeOption,
    'bi-map': MapOption,
    'bi-funnel': FunnelOption,
    'bi-gauge': GaugeOption,
    'bi-word-cloud': WordCloudOption,
    'bi-graph': GraphOption,
    'color-picker': ColorPicker,
  },
  data: () => ({
    label: {
      dataPackage: { zh: '数据包', en: 'Data Package' },
      chartParam: { zh: '图表数据', en: 'Chart Data' },
      chartOption: { zh: '图表选项', en: 'Chart Option' },
      dataWay: { zh: '数据方式', en: 'Way' },
      dataInfo: { zh: '数据包信息', en: 'Data Info' },
      title: { zh: '名称', en: 'Name' },
      updateTime: { zh: '更新时间', en: 'UpdateTime' },
      detail: { zh: '描述', en: 'Detail' },
      code: { zh: '代码', en: 'code' },
      name: { zh: '名称', en: 'name' },
      value: { zh: '值', en: 'value' },
      type: { zh: '类型', en: 'type' },
      axis: { zh: '轴', en: ' axis' },
      node: { zh: '节点', en: 'node' },
      max: { zh: '最大值', en: 'max' },
      lat: { zh: '纬度', en: 'lat' },
      lng: { zh: '经度', en: 'lng' },
      source: { zh: '来源', en: 'source' },
      target: { zh: '目标', en: 'target' },
      category: { zh: '类目', en: 'category' },
      value: { zh: '数值', en: 'value' },
      map: { zh: '地图', en: 'map' },
      theme: { zh: '主题', en: 'theme' },
      edge: { zh: '边', en: 'edge' },
      variable: { zh: '变量', en: 'variable' },
      getData: { zh: '获取数据', en: 'GET DATA' },
      view: { zh: '查看详情', en: 'VIEW DETAIL' },
      nodata: { zh: '暂无数据', en: 'NO DATA' },
      requestTip: { zh: '请求数据失败!', en: 'Fail to request data!' },
      mysqlTip: { zh: '获取MySQL数据库数失败!', en: 'Fail to get data from MySQL database' },
      createDefaultChart: { zh: '生成默认图表', en: 'CREATE DEFAULT CHART' },
      chartTitle: { zh: '图表标题', en: 'chartTitle' },
      chartTip: { zh: '请选择相关参数！', en: 'Please select params' },
      dataSourceTip: { zh: '获取数据包失败！', en: 'Fail to load data package!' },
      align: { zh: '对齐', en: ' align' },
      weight: { zh: '粗细', en: ' weight' },
      size: { zh: '大小', en: ' size' },
      bgColor: { zh: '背景颜色', en: 'BgColor' },
      titleColor: { zh: '图表标题颜色', en: 'titleColor' },
      create: { zh: '新建', en: 'CREATE' },
      save: { zh: '保存', en: 'SAVE' },
      export: { zh: '导出', en: 'EXPORT' },
      exitFullscreen: { zh: '退出全屏', en: 'EXIT FULL SCREEN' },
      fullScreen: { zh: '全屏', en: 'FULL SCREEN' },
      saveFail: { zh: '保存图表失败！', en: 'Fail to save data package!' },
      saveOK: { zh: '保存图表成功！', en: 'Succeed to save data package!' },
      update: { zh: '更新', en: 'UPDATE' },
      updateFail: { zh: '更新图表失败!', en: 'Fail to update data package!' },
      updateOK: { zh: '更新图表成功!', en: 'Succeed to update data package!' },
      titleError: { zh: '请填写至少2个字的标题!', en: 'Please input title of at least 2 words !' },
      themeTip: {
        zh: '选择了主题后一些图表选项会无效',
        en: 'Some chart options will be invalid after selected theme',
      },
    },
    //图表标题
    chartTitle: '',

    //全屏
    isFullscreen: false,
    //是否显示数据包信息
    isDataCard: false,
    //是否搜索数据包
    isSearchData: false,
    //无搜索数据包
    isSearchNone: false,
    //搜索数据包关键词
    searchOrigin: '',
    searchData: '',
    //搜索数据包结果
    dataPackages: [],
    //数据信息
    dataInfo: {
      source_id: '',
      title: '',
      detail: '',
      updateTime: new Date().format('yyyy-MM-dd hh:mm:ss'),
    },
    //主题
    themeList: ThemeList,
    //选择主题
    selectTheme: '',
    //图表类型
    chartList: ChartTypes,
    //选中图表类型
    selectChartType: 0,
    //图表数据 折线和柱形
    linebarData: { category: '', value: [] },
    //散点
    scatterData: { x: '', y: '' },
    //饼图 漏斗图 字符云 仪表盘
    pieData: { name: '', value: '' },
    //雷达图
    radarData: { name: '', max: '', value: [] },
    //树
    treeData: { name: '', node: '', value: '' },
    //地图数据
    mapData: { name: '', value: '', map: '' },
    //关系图
    relateData: { name: '', x: '', y: '', source: '', target: '', value: '', edge: '' },
    //数据类型
    types: ['string', 'number', 'date', 'datetime', 'boolean'],
    //数据包数据
    dataList: [],
    //数据包属性
    dataAttr: [],
    //提示框
    isAlert: false,
    alertTip: '',
    //生成图表
    theChart: null,
    //图表选项设置
    baseOption: {
      backgroundColor: 'transparent',
    },
    //可选择地图
    mapList: MapList,
    //左侧列表高度
    listHeight: '78vh',
    //颜色选择器
    // picker: {
    //   show: false,
    //   current: '',
    // },
    //图表id
    chartId: null,
    //是否显示图表选项列表
    isShowChartOp: false,
    originOption: '',
  }),
  watch: {
    searchData() {
      if (!this.searchData) {
        this.isSearchData = false;
      }
    },
    selectTheme() {
      var that = this;
      if (this.selectTheme) {
        $.get(this.API.themePath + this.selectTheme + '.json', function(res) {
          echarts.registerTheme(that.selectTheme, res);
          that.createChart(JSON.parse(that.originOption));
        });
      } else {
        that.createChart(JSON.parse(that.originOption));
      }
    },
    dataList() {
      if (!this.chartId) {
        this.resetChart();
      }
    },
    selectChartType() {
      if (!this.chartId) {
        this.resetChart();
      }
    },
  },
  methods: {
    resetChart() {
      //图表数据 折线和柱形
      this.linebarData = { category: '', value: [] };
      //散点
      this.scatterData = { x: '', y: '' };
      //饼图 漏斗图 字符云 仪表盘
      this.pieData = { name: '', value: '' };
      //雷达图
      this.radarData = { name: '', max: '', value: [] };
      //树
      this.treeData = { name: '', node: '', value: '' };
      //地图数据
      this.mapData = { name: '', value: '', map: '' };
      //关系图
      this.relateData = { name: '', x: '', y: '', source: '', target: '', value: '', edge: '' };
      if (this.theChart) {
        this.theChart.dispose();
        this.theChart = null;
      }
    },
    // showColorPicker(tag) {
    //   if (tag != this.picker.current || !this.picker.show) {
    //     this.picker.current = tag;
    //     this.picker.show = true;
    //   } else {
    //     this.picker.show = false;
    //   }
    // },
    // onColorPicker(op) {
    //   if (this.picker.current)
    //   this.chartTitle.color = op.rgba;

    // },
    //获取数据变量设置
    getDataOp() {
      var dataOp = null;
      var type = this.chartList[this.selectChartType].name;
      if (type == 'line' || type == 'bar') {
        //折线和柱形
        dataOp = this.linebarData;
      } else if (type == 'pie' || type == 'funnel' || type == 'word-cloud' || type == 'gauge') {
        //饼图 漏斗图 字符云 仪表盘
        dataOp = this.pieData;
      } else if (type == 'scatter') {
        //散点
        dataOp = this.scatterData;
      } else if (type == 'radar') {
        //雷达图
        dataOp = this.radarData;
      } else if (type == 'tree') {
        //树
        dataOp = this.treeData;
      } else if (type == 'map') {
        //地图
        dataOp = this.mapData;
      } else if (type == 'graph') {
        //关系图
        dataOp = this.relateData;
      }
      return dataOp;
    },

    /**生成图表数据 */
    createChartData(baseOption) {
      if (baseOption instanceof MouseEvent) {
        baseOption = null;
      }

      var isOrigin = baseOption ? false : true;
      var dataOp = this.getDataOp();
      var type = this.chartList[this.selectChartType].name;

      if (type == 'map') {
        baseOption = ChartDataUtil.createChartData(
          type,
          dataOp,
          this.dataList,
          baseOption,
          this.mapData.map
        );

        if (!baseOption) {
          this.alertTip = this.getLangText(this.label.chartTip);
          this.isAlert = true;
          return;
        }

        this.createMap(baseOption, this.mapData.map);
        this.originOption = isOrigin
          ? JSON.stringify(baseOption)
          : JSON.stringify(
              ChartDataUtil.createChartData(type, dataOp, this.dataList, null, this.mapData.map)
            );
      } else {
        baseOption = ChartDataUtil.createChartData(type, dataOp, this.dataList, baseOption);
        if (!baseOption) {
          this.alertTip = this.getLangText(this.label.chartTip);
          this.isAlert = true;
          return;
        }

        this.createChart(baseOption);
        this.originOption = isOrigin
          ? JSON.stringify(baseOption)
          : JSON.stringify(ChartDataUtil.createChartData(type, dataOp, this.dataList));
      }
    },
    //生成地图
    createMap(option, tag) {
      if (this.theChart) {
        this.theChart.dispose();
      }
      var that = this;
      $.get(this.API.mapPath + tag + '.json', function(geoJson) {
        echarts.registerMap(tag, geoJson);
        if (that.selectTheme) {
          that.theChart = echarts.init(
            document.getElementById('the_chart_content'),
            that.selectTheme
          );
        } else {
          that.theChart = echarts.init(document.getElementById('the_chart_content'));
        }

        that.theChart.setOption(option);
        that.baseOption = that.theChart.getOption();

        console.log(that.baseOption);
      });
    },
    //生成普通地图
    createChart(option) {
      if (this.theChart) {
        this.theChart.dispose();
      }
      if (this.selectTheme) {
        this.theChart = echarts.init(
          document.getElementById('the_chart_content'),
          this.selectTheme
        );
      } else {
        this.theChart = echarts.init(document.getElementById('the_chart_content'));
      }
      this.theChart.setOption(option);
      this.baseOption = this.theChart.getOption();

      console.log(this.baseOption);
    },
    //获取数据包数据
    loadDataSource(option) {
      var that = this;
      DataSourceUtil.loadDataSource(this.dataInfo.source_id, function(data) {
        if (data) {
          that.dataInfo.title = data.title;
          that.dataInfo.detail = data.detail;
          that.dataInfo.source_id = data.source_id;
          that.dataAttr = data.data_op;
          if (option && option.data_op) {
            that.setDataOp(JSON.parse(option.data_op));
          }

          if (data.dataList) {
            that.dataList = data.dataList;
            if (option && option.chart_option) {
              that.createChartData(JSON.parse(option.chart_option));
            }
          } else {
            if (data.source_type == 2) {
              that.alertTip = that.getLangText(that.label.mysqlTip);
              that.isAlert = true;
            } else if (data.source_type == 3) {
              that.alertTip = that.getLangText(that.label.requestTip);
              that.isAlert = true;
            }
          }
        } else {
          that.alertTip = that.getLangText(that.label.dataSourceTip);
          that.isAlert = true;
        }
      });
    },
    //查看数据包
    viewDataSource() {
      window.open(
        window.location.origin +
          window.location.pathname +
          '#/datasource?sourceId=' +
          this.dataInfo.source_id
      );
    },
//改变图表类型
    changeChart(idx) {
      this.selectChartType = idx;
    },
    /**全屏 */
    fullScreen() {
      var el = document.getElementById('the_chart_editor');

      if (!this.isFullscreen) {
        //进入全屏,多重短路表达式
        (el.requestFullscreen && el.requestFullscreen()) ||
          (el.webkitRequestFullscreen && el.webkitRequestFullscreen()) ||
          (el.mozRequestFullScreen && el.mozRequestFullScreen()) ||
          (el.msRequestFullscreen && el.msRequestFullscreen());
      } else {
        //退出全屏,三目运算符
        document.exitFullscreen
          ? document.exitFullscreen()
          : document.webkitExitFullscreen
          ? document.webkitExitFullscreen()
          : document.mozCancelFullScreen
          ? document.mozCancelFullScreen()
          : '';
      }
      this.isFullscreen = this.isFullscreen ? false : true;
      this.resizeEditor();
    },
    //搜索数据包
    searchDataPackage() {
      if (!this.searchData) {
        return;
      }
      if (this.dataPackages.length > 0 && this.searchOrigin == this.searchData) {
        this.isSearchData = true;
      } else {
        var that = this;
        var data = {
          userId: JSON.parse(window.localStorage.getItem("carweb_user")).userId,
          key: encodeURI(this.searchData),
        };
        $.post(this.API.searchDataSource, data, function(res) {
          if (res.errCode == 0) {
            for (var i = 0; i < res.data.length; i++) {
              res.data[i].title = decodeURI(res.data[i].title);
              res.data[i].detail = decodeURI(res.data[i].detail);
            }
            that.dataPackages = res.data;
          } else {
            that.isSearchNone = true;
          }
          that.isSearchData = true;
          that.searchOrigin = that.searchData + '';
        });
      }
    },
    //选中数据包
    selectDataPackage(idx) {
      this.dataInfo = this.dataPackages[idx];
      this.isSearchData = false;
    },
    //数据变量设置
    setDataOp(dataOp) {
      //转换为vue数据
      for (var key in dataOp) {
        if (dataOp[key] instanceof Array) {
          for (var i = 0; i < dataOp[key].length; i++) {
            for (var k = 0; k < this.dataAttr.length; k++) {
              if (dataOp[key][i].code == this.dataAttr[k].code) {
                dataOp[key][i] = this.dataAttr[k];
                break;
              }
            }
          }
        } else if (dataOp[key] instanceof Object) {
          for (var k = 0; k < this.dataAttr.length; k++) {
            if (dataOp[key].code == this.dataAttr[k].code) {
              dataOp[key] = this.dataAttr[k];
              break;
            }
          }
        }
      }

      var type = this.chartList[this.selectChartType].name;
      if (type == 'line' || type == 'bar') {
        //折线和柱形
        this.linebarData = dataOp;
      } else if (type == 'pie' || type == 'funnel' || type == 'word-cloud' || type == 'gauge') {
        //饼图 漏斗图 字符云 仪表盘
        this.pieData = dataOp;
      } else if (type == 'scatter') {
        //散点
        this.scatterData = dataOp;
      } else if (type == 'radar') {
        //雷达图
        this.radarData = dataOp;
      } else if (type == 'tree') {
        //树
        this.treeData = dataOp;
      } else if (type == 'map') {
        //地图

        this.mapData = dataOp;
      } else if (type == 'graph') {
        //关系图
        this.relateData = dataOp;
      }
    },
    //获取发送数据
    getPostData() {
      
      var data = {};

      data.dataOp = JSON.stringify(this.getDataOp());
      data.title = encodeURI(this.chartTitle);
      data.chartTheme = encodeURI(this.selectTheme);
      data.dataId = this.dataInfo.source_id;
      data.chartType = this.selectChartType;
      data.option = JSON.stringify(this.baseOption);
      data.userId = JSON.parse(window.localStorage.getItem("carweb_user")).userId;
      return data;
    },
    //新建图表
    newChart() {
      this.chartId = null;
      this.chartTitle = '';
      this.resetChart();
      window.location.hash = '#/charteditor';
    },
    //保存图表
    saveChart() {
      if (!this.chartTitle ||this.chartTitle.length<2) {
        this.isShowChartOp = true;
        return;
      }
      var data = this.getPostData();
      var that = this;
      $.post(this.API.saveChart, data, function(res) {
        if (res.errCode == 0) {
          that.chartId = res.data;
          that.alertTip = that.getLangText(that.label.saveOK);
        } else {
          that.alertTip = that.getLangText(that.label.saveFail);
        }
        that.isAlert = true;
      });
    },
    //更新图表
    updateChart() {
      if (!this.chartTitle ||this.chartTitle.length<2) {
        this.isShowChartOp = true;
        return;
      }
      var data = this.getPostData();
      data.chartId = this.chartId;
      var that = this;
      $.post(this.API.updateChart, data, function(res) {
        if (res.errCode == 0) {
          that.alertTip = that.getLangText(that.label.updateOK);
        } else {
          that.alertTip = that.getLangText(that.label.updateFail);
        }
        that.isAlert = true;
      });
    },
    //导出图表
    exportChart() {
      ExportUtil.exportImage(document.getElementById('the_chart_card'));
    },
    //获取图表
    getChartById(id) {
      this.chartId = id;
      var that = this;
      $.post(this.API.getChart, { chartId: id }, function(res) {
        if (res.errCode == 0) {
          var option = res.data[0];

          that.selectChartType = option.chart_type;
          that.selectTheme = option.chart_theme ? option.chart_theme : '';

          that.chartTitle = decodeURI(option.title);

          that.dataInfo.source_id = option.data_id;
          that.loadDataSource(option);
        } else {
          that.alertTip = that.getLangText(that.label.chartFail);
          that.isAlert = true;
        }
      });
    },
    //调整界面适配
    resizeEditor() {
      if (this.theChart) {
        this.theChart.resize(
          this.theChart.getDom().offsetWidth,
          this.theChart.getDom().offsetHeight
        );
      }
      this.listHeight = document.getElementsByTagName('body')[0].offsetHeight - 50 * 4 + 'px';
    },
  },
  mounted() {
    var that = this;
    var body = document.getElementsByTagName('body')[0];
    this.listHeight = body.offsetHeight - 50 * 4 + 'px';
    body.onresize = function() {
      that.resizeEditor();
    };
    
    var address = window.location.hash;
    if (address.indexOf('chartId') >= 0) {
      var chartId = address.split('=')[1];
      this.getChartById(chartId);
    }
  },
};
